// pages/subfriend/subfriend.js
var app=getApp();
import regeneratorRuntime from '../../utils/regenerator-runtime/runtime.js'
import {
  wxUpload
} from '../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    imgPath:app.globalData.imgPath,
    content:'',//评论内容
    tempFilePaths:[],//图片临时路径
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  upImg:function(){
    let self=this;
    wx.chooseImage({
      count: 9 - this.data.imgs.length,
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        let size=res.tempFiles[0].size;
        self.setData({tempFilePaths:tempFilePaths});
        self.uploadImg(tempFilePaths, 0);
        
      }
    })
  },
  del:function(e){//删除图片
    let index=e.currentTarget.dataset.index;
    let imgs=this.data.imgs;
      imgs.splice(index,1);
     this.setData({imgs:imgs}) 
  },
  changecontent:function(e){//输入内容
    this.setData({content:e.detail.value})
  },
  sub:function(){//发表
    let content = this.data.content;
    let imgs=this.data.imgs;
    if(content==""&&imgs.length==0){
      return false;
    }
    wx.showLoading({
      title: '上传中',
      mask: true
    })
      let data={
        type:1,
        content:content,
        imgs:imgs.join()
      }
      wx.request({
        url:app.globalData.reqPath+'shop/Comments',
        method:'POST',
        header:{
          'authorization': app.globalData.authorization
        },
        data:data,
        success:function({data}){
          if(data.code==200){
            wx.hideLoading()
            wx.switchTab({
              url: '/pages/friend/friend',
            })
          }
        }
      })
      
  },
  uploadImg: async function (teimgs, i) {
    let files = teimgs;
    i ? i : 0
    let len = files.length;
    let self = this;
    let imgs = this.data.imgs;
    if (i < len) {
      await wxUpload(app.globalData.reqPath + 'shop/upload', { file: files[i], 'authorization': app.globalData.authorization }).then(function (res) {
        console.log(res)
        let result = JSON.parse(res)
        if (result.code == 200) {
          i++;
          console.log(i)
          imgs.push(result.data);
          self.setData({ imgs: imgs})
          self.uploadImg(self.data.tempFilePaths,i)
        }
      })
    }

  }
})